package com.wyg.epdata.util.file;

import com.wyg.epdata.common.constant.BaseConstant;
import com.wyg.epcommonbase.common.exception.ExceptionEnum;
import com.wyg.epcommonbase.common.exception.MyException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @Author: WangYongGan
 * @Date: 2021/11/8 21:37
 * @Description:
 */
@Slf4j
public class FileUtil {
    public static void saveFIle(String s, String path) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        PrintWriter printWriter = new PrintWriter(fileOutputStream);
        printWriter.println(s);
        printWriter.close();
        fileOutputStream.close();
    }

    @SneakyThrows
    public static void waitDownloadFile(String path) {
        File f = new File(path);
        Date begin = new Date();
        while (!f.exists()) {
            Thread.sleep(100);
            f = new File(path);
            if ((new Date().getTime() - begin.getTime()) / 1000 > BaseConstant.waitDownloadFile)
                throw new MyException(ExceptionEnum.waitDownloadFileError);
        }
    }

    @SneakyThrows
    public static boolean downloadFile(String filePath, String fileName, String encoding, HttpServletResponse response) {

        response.setHeader("content-disposition", "attachment; filename=" + fileName);
        response.setCharacterEncoding("utf-8");
        //获取要下载的文件输入流
        InputStream in = new FileInputStream(filePath);
        int len = 0;
        //创建数据缓冲区
        byte[] buffer = new byte[1024];
        //通过response对象获取outputStream流
        OutputStream out = response.getOutputStream();
        //将FileInputStream流写入到buffer缓冲区
        while ((len = in.read(buffer)) > 0)
            out.write(buffer, 0, len);//使用OutputStream将缓冲区的数据输出到浏览器
        in.close();
        return true;
    }

    public static void deleteFile(String path) {
        File file = new File(path);
        file.delete();
    }
}
